import { defineConfig, loadEnv, type ConfigEnv, type UserConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { fileURLToPath } from 'url';
import { visualizer } from 'rollup-plugin-visualizer';
import svgLoader from 'vite-svg-loader' // 1. 引入插件

export default defineConfig(({ mode }: ConfigEnv): UserConfig => {
  // 获取当前工作目录
  const root = process.cwd();
  // 获取环境变量
  const env = loadEnv(mode, root);
  return {
    root,
    base: '/',
    publicDir: fileURLToPath(new URL('./public', import.meta.url)),
    assetsInclude: fileURLToPath(new URL('./src/assets', import.meta.url)),
    plugins: [
      vue(),
      svgLoader(),
    ],
    server: {
      host: true,
      port: 3030,
      open: true,
      cors: true,
      proxy: {
        [env.VITE_APP_API_BASEURL]: {
          target: env.VITE_BASE_API,
          changeOrigin: true
        },
      },
    },
    build: {
      sourcemap: false,
      chunkSizeWarningLimit: 500,
      rollupOptions: {
        input: {
          index: fileURLToPath(new URL('./index.html', import.meta.url)),
        },
        plugins: [visualizer({ open: true })],
        output: {
          experimentalMinChunkSize: 30 * 1024,
          format: 'esm',
          chunkFileNames: 'static/js/[name]-[hash].js',
          entryFileNames: 'static/js/[name]-[hash].js',
          assetFileNames: 'static/[ext]/[name]-[hash].[ext]',
          manualChunks(id) {
            if (id.includes('node_modules')) {
              return 'vendor';
            }
          },
        },
      },
    },
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
        '#': fileURLToPath(new URL('./types', import.meta.url)),
      },
    },
  }
})
